#!/bin/sh
# Splash Screen Control
# This service controls length of video/picture displayed during startup
# by cyperghost aka lala on discord

splash_autoplay ()
{
    local count=0
    while [ $count -lt 90 ]
    do
        sleep 1
        count=$((count+1))
        kill -0 $PID 2>/dev/null || break
    done
}

splash_default_rpi ()
{
    # Stop the video when ready
    # Wait for emulationstation or Kodi, but not more than 20 seconds
    local count=0
    while [ ! -f "/tmp/emulationstation.ready" -a ! -e "/var/run/kodi.msg" -a $count -lt 20 ]
    do
        sleep 1
        count=$((count+1))
    done
    kill -9 $PID 2>/dev/null
}

#### MAIN ####

ARCH=$(cat /usr/share/batocera/batocera.arch)

case $1 in
    start)
        # Is service is active?
        if [ -f "/var/run/user-splash-image.pid" ]; then
            picture=1
        elif [ -f "/var/run/user-splash.pid" ]; then
            picture=0
            PID=$(cat /var/run/user-splash.pid)
        else
            echo "$0: No video or image service found!" >&2
            exit 0
        fi

        # Read Config and set some defaults
        splash_setting="$(/usr/bin/batocera-settings-get splash.screen.length)"
        [ -z "$splash_setting" ] && splash_setting=auto
        [ "$splash_setting" = "auto" -a "$(echo $ARCH | cut -c 1-3)" = "rpi" -a "$(echo $ARCH | cut -c 1-3)" = "bcm" ] && splash_setting=$ARCH
        case "$splash_setting" in
            bcm2835)
                # Standard BATOCERA setting, for Pi platform with OMX Player
                #
                splash_default_rpi &
            ;;
            auto|bcm2836|bcm2837|bcm2711)
                # Play video as long as possible, ideal for fast boards
                #
                [ $picture -eq 0 ] && splash_autoplay
                start-stop-daemon -K -q -p /var/run/user-splash.pid
            ;;
            [0-90]*)
                # Stop as long as setted. 90s max for video, 10s max for images
                sleeptimer=$(echo "$splash_setting" | grep -Eo [0-9] | tr -d "\n")
                [ $picture -eq 1 -a $sleeptimer -gt 10 ] && sleeptimer=10
                sleep $sleeptimer
                start-stop-daemon -K -q -p /var/run/user-splash.pid
            ;;
            fastboot|*)
                # fastboot or invalid settings
                #
                start-stop-daemon -K -q -p /var/run/user-splash.pid
            ;;
        esac
    ;;
    stop)
    ;;
    *)
        echo "Usage $0 {start|stop}"
esac
exit 0
